package com.cxcs.cxcsojcodesandbox.Controller;

import com.cxcs.cxcsojcodesandbox.CodeSandBox;
import com.cxcs.cxcsojcodesandbox.model.ExecuteCodeRequest;
import com.cxcs.cxcsojcodesandbox.model.ExecuteCodeResponse;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 远程代码沙箱 接口交互
 *
 * @Author: CxCS
 * @Version: 1.0
 * @Date: 2024-08
 */
@RestController
@RequestMapping("/code")
public class RemoteCodeSandBoxController {
    // 定义鉴权请求头和密钥
    private static final String AUTH_REQUEST_HEADER = "auth";

    private static final String AUTH_REQUEST_SECRET = "secretKey";

    @Resource
    private CodeSandBox codeSandBox;

    /**
     *  接口获取代码 调用沙箱执行代码
     *
     * @param executeCodeRequest
     * @return
     */
    @PostMapping("/execute")
    ExecuteCodeResponse executeCode(@RequestBody ExecuteCodeRequest executeCodeRequest, HttpServletRequest request,
                                    HttpServletResponse response) {
        // 基本的认证
        String authHeader = request.getHeader(AUTH_REQUEST_HEADER); // 获取请求头
        if (!AUTH_REQUEST_SECRET.equals(authHeader)) {
            response.setStatus(403);
            return null;
        }
        if (executeCodeRequest == null) {
            throw new RuntimeException("请求参数为空");
        }
        return codeSandBox.executeCode(executeCodeRequest);
    }

}
